#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4 sw=4 et ai ft=python nowrap

import os
import re
import urllib2
import webbrowser
import wallpaper

try:
    if os.name == 'nt':
        import Image  # Requires the PIL Library
except:
    print 'Python Imaging Library module is required for this application'


class DesktopWallpaper:

    """Comment."""

    def __init__(self, proxy=None):
        """Comment"""

        if proxy:
            PROXY_IP = proxy['IP']
            PROXY_USER = proxy['USER']
            PROXY_PASSWORD = proxy['PASSWORD']
            PROXY_PORT = proxy['PORT']

            proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + \
                '@' + PROXY_IP + ':' + PROXY_PORT
            proxy_support = urllib2.ProxyHandler({'http': proxy_url})
            opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
            urllib2.install_opener(opener)

    def readflickrin(self):
        """Comment"""

        SITEURL = 'http://flickr.com/explore/interesting/'
        req = urllib2.Request(SITEURL)
        content = urllib2.urlopen(req).read()

        return content

    def lookforwallpaper(self, content):
        """Comment"""

        lookfor = re.compile('One\\ of\\ the\\ most.*img\\ src="(.*\\.jpg)')
        wallpaper = lookfor.search(content).group(1)
        return wallpaper

    def downloadjpg(self, wallpaper):
        """Comment"""

        req = urllib2.Request(wallpaper)
        data = urllib2.urlopen(req).read()
        jpgimgfile = 'Wallpaper.jpg'
        imgfile = open(jpgimgfile, 'wb')
        imgfile.write(data)
        imgfile.close()
        path = os.getcwd() + os.sep + jpgimgfile

    def downloadbmp(self, wallpaper):
        """Comment"""

        bmpimgfile = 'Wallpaper.bmp'
        Image.open(wallpaper).save(bmpimgfile, 'BMP')
        path = os.getcwd() + os.sep + bmpimgfile
        return path

    def setwallpwindows(self, path):
        """Comment"""

        try:
            import win32api
            import win32gui
            import win32con
        except:

   #from win32con import SPI_SETDESKWALLPAPER

            print 'Win32 extensions for python needs to be installed.'

  #k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
  #win32api.RegSetValueEx(k,"WallpaperStyle", 0, win32con.REG_SZ, "0")
  #win32api.RegSetValueEx(k,"TileWallpaper", 0, win32con.REG_SZ, "0")

        win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, 
                path, 0)

    def setwallplinux(self, path):
        """Comment"""

        try:
            import gconf
        except ImportError:
            print 'Gnome Python Library Error. Please Install.'
        obj = gconf.client_get_default()
        obj.set_string('/desktop/gnome/background/picture_filename', 
                       path)


def run(proxy=None):
    """Run"""

    wallp = DesktopWallpaper(proxy)
    buzzwallpaper = wallpaper.get_buzz_wallpaper()
    if os.name == 'nt':
        storebmp = wallp.downloadbmp(buzzwallpaper)
        wallp.setwallpwindows(storebmp)
    elif os.name == 'posix':
        storejpg = wallp.downloadjpg(buzzwallpaper)
        wallp.setwallplinux(storejpg)


if __name__ == '__main__':
    run()
